package com.whfc.emp.websocket;

import com.whfc.common.third.helmet.HelmetProperties;
import com.whfc.emp.helmet.ZbznVideoParse;
import lombok.Setter;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft_6455;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;

public class ZbznWebSocketClient extends WebSocketClient {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    public boolean WEBSTATUS = false;

    @Setter
    private ZbznVideoParse zbznVideoParse;

    @Setter
    private HelmetProperties helmetProperties;

    //连接
    public ZbznWebSocketClient(URI serverUri) {
        super(serverUri,new Draft_6455());
    }

    public void sendMockMsg(String message){
        if (!helmetProperties.isRunnable()) return;
        logger.info("mock websocket客户端收到消息={}", message);
        //接收消息
        try {
            zbznVideoParse.parseMassage(message);
        } catch (Exception e) {
            logger.info("解析指令异常 {}", e.getMessage());
        }
    }

    @Override
    public void reconnect() {
        if (!helmetProperties.isRunnable()) return;
        logger.info("断线重连");
        super.reconnect();
    }

   //打开连接
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        if (!helmetProperties.isRunnable()) return;
        logger.info("websocket客户端和服务器连接成功");
        this.WEBSTATUS = true;
    }

    @Override
    public void onMessage(String message) {
        if (!helmetProperties.isRunnable()) return;
        logger.info("websocket客户端收到消息={}", message);
        //接收消息
        try {
            zbznVideoParse.parseMassage(message);
        } catch (Exception e) {
            logger.info("解析指令异常 {}", e.getMessage());
        }
    }

    @Override
    public void onClose(int code, String reason, boolean bremote) {
        if (!helmetProperties.isRunnable()) return;
        logger.info("websocket客户端退出连接");
        this.WEBSTATUS = false;
    }

    @Override
    public void onError(Exception ex) {
        logger.info("websocket客户端和服务器连接发生错误={}", ex.getMessage());
    }
    //推送消息
    public void sendMsg(String msg){
        if (!helmetProperties.isRunnable()) return;
        if(this.WEBSTATUS){
            send(msg);
        }
    }

}
